<?php
/**
 * CreateTime: 2023/2/17 14:59
 */

namespace App\Http\Controllers\MeSms;

use App\Consts\ResponseConsts\ResponseStatusConsts;
use App\Consts\TableConsts\TableConsts;
use App\Func\DictionaryFunc;
use App\Func\ResponseFunc;
use App\Func\TokenFuc;
use App\Http\Controllers\Controller;
use App\Http\Requests\ListBasicRequest;
use App\Http\Requests\Sms\SendSMSRequest;
use App\Models\MeClient\MeClientModel;
use App\Models\MeLawCase\MeLawCase;
use App\Models\MeLawCase\MeLawCaseLawLetterModel;
use App\Models\MeLawCase\MeLawCasePhoneModel;
use App\Models\ShortLink\ShortLinkModel;
use App\Models\SMS\SMSCallbackModel;
use App\Models\SMS\SMSLogModel;
use App\Models\SMS\SMSTemp;
use App\Models\SMS\SMSUpstreamModel;
use App\Tools\QxwgSMS\QxwgController;
use App\Tools\QxwgSMS\QxwgSmsClient;
use App\Tools\Sms\DbaicaiSms;

class MeSMSController extends Controller
{
    private function replaceTemp($lawCaseInfo,$tempContent){
        // 替换被申请人
        if (strpos($tempContent, '{%respondent_name%}') !== false){
            $tempContent = str_replace("{%respondent_name%}", $lawCaseInfo['respondent_name'], $tempContent);
        }
        // 替换平台方
        if (strpos($tempContent, '{%applicant_name%}') !== false){
            $tempContent = str_replace("{%applicant_name%}",$lawCaseInfo['applicant_name'], $tempContent);
        }

        // 替换案件类型
        if (strpos($tempContent, '{%law_case_type_str%}') !== false){
            $tempContent = str_replace("{%law_case_type_str%}",$lawCaseInfo['law_case_type_str'], $tempContent);
        }
        // 替换手机号
        if (strpos($tempContent, '{%phone%}') !== false){
            $tempContent = str_replace("{%phone%}","028-61114211", $tempContent);
        }
        // 替换委托方
        if (strpos($tempContent, '{%client_name%}') !== false){
            // 查询客户id
            $clientModel = new MeClientModel();
            $clientInfo = $clientModel->getById($lawCaseInfo['client_id'],['client_name']);
            $tempContent = str_replace("{%client_name%}", $clientInfo['client_name'], $tempContent);
        }
        // 替换短连接
        if (strpos($tempContent, '{%link_url%}') !== false){
            // 查询当前案件短链接code
            $latterModel = new MeLawCaseLawLetterModel();
            $latterInfo = $latterModel->getByLawCaseId($lawCaseInfo['law_case_id']);
            if(isset($latterInfo['short_link_id'])){
                $shortInfo = (new ShortLinkModel())->where('short_link_id',$latterInfo['short_link_id'])->first();
                $tempContent = str_replace("{%link_url%}", 'https://t.cyhzsoft.com/'.$shortInfo['short_link_code'], $tempContent);
            }else{
                return false;
            }
        }
        $tempContent = str_replace(["\r","\n","\t"], "", $tempContent);
        return $tempContent;
    }


    /**
     * 一对一发送短信
     * @return \Illuminate\Http\JsonResponse
     */
    public function sendSMS(SendSMSRequest $request){
        $client = new QxwgController();
        $data = $request->all();
        // 生成短信配置data
        $lawCaseModel = new MeLawCase();
        $lawCasePhoneModel = new MeLawCasePhoneModel();
        $tempModel = new SMSTemp();
        // 查询模板
        $tempId = $data['temp_id'];
        $tempInfo = $tempModel->getById($tempId);
        $tempStr = "";
        if($tempInfo&&isset($tempInfo['temp_content'])){
            $tempStr = $tempInfo['temp_content'] ;
        }

        if(!$tempStr){
            return ResponseFunc::returnJson(
                'error',
                null,
                "短信模板错误",
                ResponseStatusConsts::OK_200_RESPONSE_STATUS,
            );
        }
        $messageList = [];
        $smsLogList  = [];
        // 记录成功的发送短信
        $successSMSArray = [];
        // 记录失败的发送短信
        $failSMSArray = [];
        // 获取案件类型字典键值对
        $diInfo = DictionaryFunc::getDictionaryNodeByDictionKey('ME_LAW_CASE_TYPE',['dictionary_name','dictionary_value']);
        $diIdDiValueArr = array_column($diInfo->toArray(),'dictionary_name','dictionary_value');
        $allCount = count($data['law_case_ids']);
        if($allCount>=500){
            return ResponseFunc::returnJson(
                'error',
                null,
                "一次最多发送500个短信",
                ResponseStatusConsts::OK_200_RESPONSE_STATUS,
            );
        }
        // 实例化短信记录类
        $smsLogModel = new SMSLogModel();

        foreach($data['law_case_ids'] as $value){
            // 获取主叫号码
            $lawCaseInfo = $lawCaseModel->select([
                'law_case.law_case_id',
                'law_case.law_case_type_id',
                'law_case.respondent_name',
                'law_case.client_id',
                'law_case.main_respondent_phone_id',
                'law_case.law_case_code',
                'law_case.applicant_name'
            ]) ->where('law_case_id',$value)->first();
            $phoneNumber = isset($lawCasePhoneModel->select(['phone_number'])->where('law_case_phone_id',$lawCaseInfo['main_respondent_phone_id'])->first()['phone_number'])
                ? $lawCasePhoneModel->select(['phone_number'])->where('law_case_phone_id',$lawCaseInfo['main_respondent_phone_id'])->first()['phone_number'] : false;
            // 校验当前用户当前模板是否已经发送过短信了
            $isExists = $smsLogModel->isExistByCondition([
                'law_case_id' => $lawCaseInfo['law_case_id'],
                'temp_sms_id' => $tempId,
            ]);
//            if($isExists){
//                $failSMSArray[$phoneNumber] = "禁止重复发送";
//                continue;
//            }

            if($tempId == 7 && !$lawCaseInfo['applicant_name']){
                $failSMSArray[$phoneNumber] = "申请人不存在";
                continue;
            }

            if(!$phoneNumber){
                $failSMSArray[$phoneNumber] = "手机号不存在或已删除";
                continue;
            }
//            if(!isset($diIdDiValueArr[$lawCaseInfo['law_case_type_id']])){
//                // 不存在则跳过这个案件
//                $failSMSArray[$phoneNumber] = "案件类型错误";
//                continue;
//            }

            // $lawCaseInfo['law_case_type_str'] = $diIdDiValueArr[$lawCaseInfo['law_case_type_id']];
            // $tempContent = $this->replaceTemp($lawCaseInfo,$tempStr);
//            if(!$tempContent){
//                $failSMSArray[$phoneNumber] = "短链接生成失败";
//                continue;
//            }

            // 获取主叫号码
            $messageList[$phoneNumber] = $tempStr;
            $smsLogList[$phoneNumber] = [
                'phone' => $phoneNumber,
                'sms_info' => $tempStr,
                'law_case_id' => $value,
                'temp_sms_id' => $tempId,
                'owner_id' => TokenFuc::getCurrentStaffInfo()['staff_id'] ?? 0
            ];
        }

        if(!$messageList){
            return ResponseFunc::returnJson(
                'ok',
                [
                    'total_count' => $allCount,
                    'success_count' => 0,
                    'fail_count' => count($failSMSArray),
                    'fail_list' => $failSMSArray,
                    'success_list' => $successSMSArray
                ],
                "短信发送成功",
                ResponseStatusConsts::OK_200_RESPONSE_STATUS,
            );
        }

        $data = $client->p2pSendSms($messageList);

        foreach($data as $key => $value){
            if($value['result']!=0){
                $failSMSArray[$value['mobile']] = '运营商短信发送错误code'.$value['result'];
                # 删除失败的短信日志
                unset($smsLogList[$value['mobile']]);
            }else{
                $successSMSArray[$value['mobile']] = "ok";
            }
        }


        foreach($smsLogList as $value){
            $smsLogModel->add($value);
        }


        return ResponseFunc::returnJson(
            'ok',
            [
                'total_count' => $allCount,
                'success_count' => count($successSMSArray),
                'fail_count' => count($failSMSArray),
                'fail_list' => $failSMSArray,
                'success_list' => $successSMSArray
            ],
            "短信发送成功",
            ResponseStatusConsts::OK_200_RESPONSE_STATUS,
        );
    }

    public function getSmsTempList(ListBasicRequest $request){
        $pFilters = $request->get('filters');
        $pageSize = $request->get('page_size');
        return ResponseFunc::returnJson(
            'ok',
            $this->workbenchService->getSelfAgendaList($pageSize,$pFilters),
            '获取我的待办成功',
            ResponseStatusConsts::OK_200_RESPONSE_STATUS
        );
    }

    public function getSmsTemp(){
        $client = DbaicaiSms::getInstance();
        $client->changeRequestType('POST');
//        $templateId = request()->all()['tempId'];
        $data = $client->getSMSTemp();
//        $data['templateId'] = $templateId;
        $res = $client->execute('api/queryTemplate',$data);
        $fmtRes = json_decode($res,true);
        if($fmtRes['code']){
            return ResponseFunc::returnJson(
                'error',
                null,
                $fmtRes['message'],
                ResponseStatusConsts::OK_200_RESPONSE_STATUS,
            );
        }
        return ResponseFunc::returnJson(
            'ok',
            $fmtRes['data'],
            "短信模板获取成功",
            ResponseStatusConsts::OK_200_RESPONSE_STATUS,
        );
    }

    public function addSmsTemp(){
        $client = DbaicaiSms::getInstance();
        $client->changeRequestType('POST');
//        $data = $client->addSMSTemp("【亿展达2】{%c_name%}的登录验证码是：{%c_code%}");
        $data = $client->addSMSTemp("【弋阳昊元调解中心】{%user_name%} ，关于你方与（ {%platform_name%} ）民事纠纷案件，经多次协调未果现已进行司法公开，详情可查询“弋阳法院”微 信官方公众号—“司法公开”—“弋阳昊元人民调解查询” 详询：{%phone%} 。退订回T");
        $res = $client->execute('api/addTemplate',$data);
        $fmtRes = json_decode($res,true);

        if($fmtRes['code']){
            return ResponseFunc::returnJson(
                'error',
                null,
                $res,
                ResponseStatusConsts::OK_200_RESPONSE_STATUS,
            );
        }
        return ResponseFunc::returnJson(
            'ok',
            [
                'tempId' => $fmtRes['templateId']
            ],
            "短信模板新增成功",
            ResponseStatusConsts::OK_200_RESPONSE_STATUS,
        );
    }

    /**
     * 上行回复获取接口
     * @return \Illuminate\Http\JsonResponse
     */
    public function getUpstream(ListBasicRequest $request){
        $pFilters = $request->get('filters');
        $pageSize = $request->get('page_size');
        $filters = $pFilters ? json_decode($pFilters, true) : [];
        $client = DbaicaiSms::getInstance();
        $client->changeRequestType('POST');
        $data = $client->getUpstream();
        $res = $client->execute('api/getUpstream',$data);
        $fmtRes = json_decode($res,true);
        $smsUp = new SMSUpstreamModel();
        if($fmtRes['code']){
// 暂时屏蔽运营商报错 用于返回列表
//            return ResponseFunc::returnJson(
//                'error',
//                null,
//                $fmtRes['message'],
//                ResponseStatusConsts::OK_200_RESPONSE_STATUS,
//            );
        }else{
            // 当运营商没有返回报错的时候再填充数据进入数据库
            foreach($fmtRes['data'] as $value){
                $smsUp->add([
                    'phone' => $value['phone'],
                    'content' => $value['content'],
                    'receiveTime' => $value['receiveTime'],
                ]);
            }
        }
        $query = $smsUp->select([
           'law_case_sms_upstream_id',
           'law_case_sms_upstream_id as key',
           'phone',
           'content',
           'receiveTime',
        ]);
        if(isset($filters['phone'])){
            $query = $query->where('phone','LIKE',"%".$filters['phone']."%");
        }
        $data = $smsUp->getListNoTimeNotStatus($query,$pageSize)->toArray() ?? [];
        return ResponseFunc::returnJson(
            'ok',
            $data,
            "上行回复获取成功",
            ResponseStatusConsts::OK_200_RESPONSE_STATUS,
        );
    }

    /**
     * 上行回复获取接口V2 QXWG
     * @return \Illuminate\Http\JsonResponse
     */
    public function getUpstreamV2(ListBasicRequest $request){
        $pFilters = $request->get('filters');
        $pageSize = $request->get('page_size');
        $filters = $pFilters ? json_decode($pFilters, true) : [];
        $client = DbaicaiSms::getInstance();
        $client->changeRequestType('POST');
        $data = $client->getUpstream();
        $res = $client->execute('api/getUpstream',$data);
        $fmtRes = json_decode($res,true);
        $smsUp = new SMSUpstreamModel();
        if($fmtRes['code']){
// 暂时屏蔽运营商报错 用于返回列表
//            return ResponseFunc::returnJson(
//                'error',
//                null,
//                $fmtRes['message'],
//                ResponseStatusConsts::OK_200_RESPONSE_STATUS,
//            );
        }else{
            // 当运营商没有返回报错的时候再填充数据进入数据库
            foreach($fmtRes['data'] as $value){
                $smsUp->add([
                    'phone' => $value['phone'],
                    'content' => $value['content'],
                    'receiveTime' => $value['receiveTime'],
                ]);
            }
        }
        $query = $smsUp->select([
           'law_case_sms_upstream_id',
           'law_case_sms_upstream_id as key',
           'phone',
           'content',
           'receiveTime',
        ]);
        if(isset($filters['phone'])){
            $query = $query->where('phone','LIKE',"%".$filters['phone']."%");
        }
        $data = $smsUp->getListNoTimeNotStatus($query,$pageSize)->toArray() ?? [];
        return ResponseFunc::returnJson(
            'ok',
            $data,
            "上行回复获取成功",
            ResponseStatusConsts::OK_200_RESPONSE_STATUS,
        );
    }

    public function getCallBackByDabaicai(){
        $client = DbaicaiSms::getInstance();
        $client->changeRequestType('POST');
        $data = $client->getReport();
        $res = $client->execute('api/getReport',$data);
        $fmtRes = json_decode($res,true);
        $smsCallBackModel = new SMSCallbackModel();
        $data = $fmtRes['data'];
        foreach($data as $key => $value){
            $smsCallBackModel->add([
                'msg_id' => $value['msgId'],
                'type_str' => '大白菜',
                'receive_time' => $value['receiveTime'],
                'status' => $value['status'],
                'phone' => $value['phone']
            ]);
        }
        dd($fmtRes);
    }

}